﻿using Microsoft.Owin.Security.OAuth;
using System.Collections.Generic;
using Microsoft.Owin.Security;
using System.Security.Claims;
using System.Threading.Tasks;

namespace King.Box.WebApi.Providers.Impl
{
    internal class OAuthServerProvider : OAuthAuthorizationServerProvider
    {
        private readonly IAuthService _authService;
        public OAuthServerProvider(IAuthService authService)
        {
            _authService = authService;
        }

        public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
        {
            string clientId, clientSecret;
            context.TryGetBasicCredentials(out clientId, out clientSecret);

            if (!_authService.VailedClient(clientId, clientSecret))
            {
                context.SetError("invalid_client");
                return;
            }

            context.Validated(clientId);
            await base.ValidateClientAuthentication(context);
        }

        public override async Task GrantClientCredentials(OAuthGrantClientCredentialsContext context)
        {
            var oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.ClientId));
            oAuthIdentity.AddClaim(new Claim(ClaimTypes.Role, ClientAuthorize.Client));

            var dictionary = new Dictionary<string, string> { { "as:client_id", context.ClientId ?? string.Empty } };
            var props = new AuthenticationProperties(dictionary);
            var ticket = new AuthenticationTicket(oAuthIdentity, props);

            context.Validated(ticket);
            await base.GrantClientCredentials(context);
        }

        /*public override Task TokenEndpoint(OAuthTokenEndpointContext context)
        {
            foreach (KeyValuePair<string, string> property in context.Properties.Dictionary)
            {
                context.AdditionalResponseParameters.Add(property.Key, property.Value);
            }
            return Task.FromResult<object>(null);
        }*/
    }
}
